<!-- 创建订单 -->
<template>
	<view class="container">
		<!-- ‘代驾 跑腿 创单’栏位 -->
		<view class="content-field">
			<view class="service-tabs">
				<view class="tab-item" :class="{ 'active': selectedService === '代驾' }" @click="selectService('代驾')">
					<text class="iconfont icon-daijia"></text>
					<text class="tab-text">代驾</text>
				</view>
				<view class="tab-item" :class="{ 'active': selectedService === '跑腿' }" @click="selectService('跑腿')">
					<text class="iconfont icon-paotui"></text>
					<text class="tab-text">跑腿</text>
				</view>
			</view>
			
			<!-- 输入用户手机号码 -->
			<view class="phone" :class="{ 'error': phoneError }">
				<view class="left">
					<uni-icons type="phone" size="15" color="#67C23A"></uni-icons>
					<input 
						class="enter-phone"
						type="number" 
						placeholder="输入车主手机"
						v-model="userPhone"
						maxlength="11"
						@input="handlerEnterPhone"
					/>
				</view>
				<view class="error-tip">{{ phoneError }}</view>
			</view>
			<!--当前位置-->
			<view class="location" @tap="handlerSelectCurrent">
				<view class="left">
					<uni-icons type="location" size="15" color="#409EFF"></uni-icons>
					出发: {{ currentAddress }} >
				</view>
				<view class="right" @tap.stop="getCurrLocation"><!-- @tap.stop阻止事件冒泡 -->
					<uni-icons type="reload" size="15"></uni-icons>
				</view>
			</view>
			<!--想去哪里-->
			<view class="target" @tap="handlerSelectTarget">
				<view class="left">
					<uni-icons type="flag" size="15" color="#F56C6C"></uni-icons>
					{{ destinationAddress || '目的地' }}
				</view>
			</view>
			<view class="friend-btn-wrap">
				<button class="friend-btn" @click="handlerSubmit">创建订单</button>
			</view>
			
			<!-- 价格预算 -->
			<view class="price-box">
				<view class="left">
					<text class="text">起步价</text>
					<text class="num">￥{{ formatAmount(startPrice) }}</text>
					<view class="question" @tap="gotoAboutPage">
						<uni-icons type="help" size="18" color="#999"></uni-icons>
					</view>
				</view>
				<view class="right" v-if="totalPrice > 0">
					<text class="text">总价</text>
					<text class="num">￥{{ formatAmount(totalPrice) }}</text>
				</view>
			</view>
		</view>
		<view class="guessKmTime" v-if="distance > 0 && duration > 0">
			<text class="left">预计: {{ formatDistance(distance) }} / {{ formatDuration(duration) }}</text>
		</view>
	</view>
</template>

<script setup>
import { onMounted, onUnmounted, ref } from 'vue'
import { onPullDownRefresh, onHide, onShow, onReachBottom } from '@dcloudio/uni-app'
import { formatDatetime } from '@/utils/datetimeUtil.js'
import { auditStatusEnum } from '@/utils/enums.js'
import wsClient from '@/ws/ws-client.js'
import { formatAmount } from '@/utils/amountUtil.js'// 价格换算工具
import { formatDistance, formatDuration } from '@/utils/kmUtil.js'// 距离 时间格式化工具
import { calcPriceByDistance, checkDriverOrder, driverCreate } from '../../api/order'
import { useUserStore } from '../../stores/userStore'
import { orderTypeEnum } from '../../utils/orderType'

const driver = useUserStore()

/* 代驾 跑腿的选择 */
const selectedService = ref('代驾')
const selectService = (service) => {
	selectedService.value = service
}

// 页面类型初始 current当前位置，target目的地
const pageType = ref('target')

// 用户手机号
const userPhone = ref('')
// 手机号错误信息
const phoneError = ref('')

// 目的地
const destinationAddress = ref('')

// 起步价
const startPrice = ref(1800)
// 总价
const totalPrice = ref(0)
// 预计距离
const distance = ref(0)
// 预计时间
const duration = ref(0)

// 目标位置信息
const targetLocation = ref({})

const currentAddress = ref('获取定位中...')
const latlng = ref({ latitude: 0, longitude: 0 }) 
const AMAP_KEY = '9996b2ae4c2bd5c1caab3861243bb047'// 高德密钥

// 手机号输入
function handlerEnterPhone(e) {
	let phone = e.detail.value.replace(/[^\d]/g, '')
	if(phone.length > 11) {
		phone = phone.slice(0, 11)
	}
	userPhone.value = phone
	if(phoneError.value) {
		phoneError.value = ''
	}
}
// 手机号格式校验
function phoneFormat(phone) {
	const phoneRegex = /^1[3-9]\d{9}$/
	return phoneRegex.test(phone)
}
// 验证手机号
function validatePhone() {
	if(!userPhone.value){
		phoneError.value = '请输入手机号'
		return false
	}
	if(!phoneFormat(userPhone.value)) {
		phoneError.value = '请输入正确手机号码'
		return false
	}
	phoneError.value = ''
	return true
}

function init(){
	return new Promise((resolve, reject) => {
		uni.getLocation({
			isHighAccuracy:true,// 高精度
			type:'gcj02' ,//高德坐标系
			timeout: 15000,
			success: (res) => {
				const {latitude,longitude} = res
				latlng.value.latitude = latitude
				latlng.value.longitude = longitude
				
				//调用高德逆地理编码API
				getAddressByLatLng(longitude, latitude).then(() => {
				}).catch(e => {
					reject(e);
				})
			},
			fail: (err) => {
				console.error('系统定位失败', err)
				if (err.errMsg.includes('auth deny')) {
				  currentAddress.value = '请在系统设置中开启定位权限'
				} else {
				  currentAddress.value = '定位失败，请检查网络'
				}
				reject(err)
				
				// 位置权限拒绝后提示用户开启
				// tipOpenPosition()
			}
		})
	})
}
//逆地理编码提取市区街道门牌号
function getAddressByLatLng(lng, lat) {
	return new Promise((resolve, reject) => {
		const amapKey = '9996b2ae4c2bd5c1caab3861243bb047';
		const url = `https://restapi.amap.com/v3/geocode/regeo?location=${lng},${lat}&key=${amapKey}&extensions=base&output=json`
		
		uni.request({
			url: url,
			method: 'GET',
			success: (res) => {
				if(res.data.status === '1' && res.data.regeocode) {
					const addressComponent = res.data.regeocode.addressComponent
					
					// 提取区 街道 门牌号
					const city = addressComponent.city || ''
					const district = addressComponent.district || ''
					const street = addressComponent.streetNumber.street || ''
					const streetNumber = addressComponent.streetNumber?.number || ''
					//组合地址信息（市区街道门牌号）
					currentAddress.value = `${city}${district}${street}${streetNumber ? streetNumber : ''}`
					//如果未获得详细地址，高德返回完整地址
					if (!currentAddress.value){
						currentAddress.value = res.data.regeocode.formatted_address
					}
					resolve()
				}else{
					currentAddress.value = '获取定位失败'
					console.log('高德API错误原因：', res.data.info,  '错误码：', res.data.code)
				}
			},
			fail: (err) => {
				console.log('地址解析失败', err)
				currentAddress.value = '地址解析失败'
			}
		})
	})
}

// 选择当前位置
function handlerSelectCurrent() {
	const locationData = {
		latitude: latlng.value.latitude,
		longitude: latlng.value.longitude,
		addressInfo: {
			fullname: currentAddress.value
		}
	}
	uni.navigateTo({
		url: `/pages/create-order/search-location?city=${currentAddress.value}&currLocation=${JSON.stringify(locationData)}&type=current`
	})
}

// 输入目的地
function handlerSelectTarget() {
	const locationData = {
		latitude: latlng.value.latitude,
		longitude: latlng.value.longitude
	}
	uni.navigateTo({
		url: `/pages/create-order/search-location?city=${currentAddress.value}&currLocation=${JSON.stringify(locationData)}&type=target`
	})
}

// 如果有目的地更换当前位置，重新计算距离，时间
function recalculatePrice() {
	if(!targetLocation.value || !targetLocation.value.location) {
		console.log('没有目的地，不需要重新计算价格')
		return
	}
	
	const amapKey = '9996b2ae4c2bd5c1caab3861243bb047'
	const origin = `${latlng.value.longitude},${latlng.value.latitude}`
	const destination = `${targetLocation.value.location.lng},${targetLocation.value.location.lat}`
	const url = `https://restapi.amap.com/v3/direction/driving?key=${amapKey}&origin=${origin}&destination=${destination}&output=JSON`
	
	console.log('重新计算价格，参数:', { origin, destination })
	console.log('====================================================================================================')
	uni.request({
		url: url,
		method: 'GET',
		success: (res) => {
			if(res.data && res.data.status === '1' && res.data.route && res.data.route.paths.length > 0){
				const path = res.data.route.paths[0]
				const newDistance = path.distance
				const newDuration = path.duration
				
				const distanceKM = Math.ceil(newDistance / 1000)
				calcPriceByDistance(distanceKM).then(priceRes => {
					const newPrice = priceRes.data.toFixed(1)
					
					distance.value = newDistance
					duration.value = newDuration
					totalPrice.value = newPrice
				}).catch(err => {
					console.log('重新计算价格失败', err)
				})
			}
		},
		fail: (err) => {
			console.error('重新计算路径失败:', err)
		}
	})
}

// 监听选择的目的地
const SelectedLocation = (locationData) => {
	console.log(`接受到的目的地 类型： ${locationData.type}`, locationData)
	
	if(locationData && locationData.location){
		const location = locationData.location
		
		if(locationData.type === 'current') {
			console.log('处理当前位置选择:', location)
			// 保存当前位置
			latlng.value.latitude = location.location.lat
			latlng.value.longitude = location.location.lng
			currentAddress.value = location.fullAddress || location.name || location.address
			
			console.log('更新当前位置成功:')
			console.log('===================================================================')
			currentAddress.value = currentAddress.value
			// 如果已经选择了目的地，再更换当前位置，重新计算价格
			if(targetLocation.value.location){
				recalculatePrice()
			}
		} else {
			console.log('处理目的地选择:', location)
			// 保存目的地位置
			targetLocation.value = locationData.location
			destinationAddress.value = `${location.cityname}${location.adname}${location.name}`
			
			distance.value = locationData.dist
			duration.value = locationData.dura
			totalPrice.value = locationData.price
			console.log('================================================================================================')
		}
		
		
	}
}

// 跳转关于页面
function gotoAboutPage() {
	uni.navigateTo({
		url: '/pages/create-order/about'
	})
}

// 拒绝位置权限后提示
// function tipOpenPosition() {
	
// }

onMounted(() => {
	init()
	// 监听选择目的地事件
	uni.$on('selected-new-location', SelectedLocation)
})

onUnmounted(() => {
	// 移除监听事件，防止内存溢出
	uni.$off('selected-new-location', SelectedLocation)
})

// 跳转到详情页
function gotoInfoPage(order, status) {
	order['status'] = status
	// #ifdef APP-PLUS
	uni.navigateTo({
		url:`/pages/index/info?query=${JSON.stringify(order)}`
	})
	// #endif
	// #ifndef APP-PLUS
	uni.navigateTo({
		url:`/pages/index/info2?query=${JSON.stringify(order)}`
	})
	// #endif
}

// 提交订单
async function handlerSubmit() {
	// 校验手机号
	if(!validatePhone()){
		return
	}
	
	//校验目的地地理位置
	if(!targetLocation.value.location || !targetLocation.value.location.lat || !targetLocation.value.location.lng){
		uni.showToast({
			title: '请选择目的地',
			mask: true, //启用遮罩层
			duration: 2000 ,//显示两秒
			icon: 'none'
		})
		return
	}
	// 校验司机是否有订单正在服务
	const driverId = driver.getCurrentDriver().id
	try {
		const checkRes = await checkDriverOrder(driverId)
		if (checkRes.data && checkRes.data.length > 0) {
			uni.showModal({
				title: '提示',
				content: '您有一笔订单正在进行，请完成当前订单再创建新订单',
				showCancel: false,
				confirmText: '确定'
			})
			return 
		}
		
		// 整合订单数据
		const orderData = {
			driverId: driverId,
			userPhone: userPhone.value,
			currentLo: latlng.value.longitude,
			currentLa: latlng.value.latitude,
			currentAddr: currentAddress.value,
			targetLo: targetLocation.value.location.lng,
			targetLa: targetLocation.value.location.lat,
			targetAddr : destinationAddress.value,
			price: totalPrice.value * 1,
			status: orderTypeEnum.GET.code
		}
		uni.showModal({
			title: "创建订单",
			content: '是否确定创建该订单',
			success: (res) => {
				if (res.confirm) {
					driverCreate(orderData).then(res => {
						console.log('res的内容', res)
						if (res.status) {
							uni.showToast({
								title: "创建订单成功",
								icon: 'success'
							})
							// 成功创建订单用回调跳转详情页
							setTimeout(() => {
								const orderInfo = {
									...orderData,
									id: res.data.id,
									orderTime: res.data.orderTime,
									distance: distance.value,
									hopeTime: new Date(),
									status: orderTypeEnum.GET.code
								}
								gotoInfoPage(orderInfo, orderTypeEnum.GET.code)
							}, 1500)
						} else {
							uni.showToast({
								title: "创建订单失败",
								icon: 'none'
							})
						}	
					}).catch(error => {
						console.error('创建订单失败', error)
					})
				}
			}
		})
	} catch (error) {
		console.error('检查订单状态失败', error)
		uni.showToast({
			title: '系统异常，请重试',
			icon: 'none'
		})
	}
	
}
</script>



<style lang="scss" scoped>
view {
	box-sizing: border-box;
}
.container {
	width: 100vw;
	min-height: 100vh;
	background-color: #f8f8f8;
	padding: 30rpx;
	/* 代驾 跑腿状态区域 */
	.content-field {
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		padding: 30rpx;
		background-color: #ffffff;
		border-radius: 20rpx;
		.service-tabs {
			display: flex;
			gap: 0;
			margin-bottom: 20rpx;
		}
		.tab-item {
			flex: 1;
			text-align: center;
			padding: 20rpx 0;
			border-radius: 15rpx;
			font-size: 28rpx;
			font-weight: 600;
			color: #333;
			background-color: #f5f5f5;
			transition: all 0.2s ease;
			display: flex;
			align-items: center;
			justify-content: center;
			gap:12rpx;
			// 选中状态 白背 + 蓝字
			&.active {
				background-color: #fff;
				color: #3f89ff;
				box-shadow: 0 2rpx 8rpx rgba(41, 121, 255, 0.2);
				.iconfont {color: #3f89ff;}
			}
			&:active {transform: scale(0.98);}//点击反馈
			.iconfont {
				font-size: 50rpx;
			}
		}
		.phone, .location, .target {
			padding: 30rpx;
			border-radius: 20rpx;
			background-color: #f5f5f5;
			margin-top: 20rpx;
			font-size: 24rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			position: relative;
			&.error {
				background-color: #fef0f0;
				border: 1rpx solid #f56c6c;
			}
			.left {
				display: flex;
				align-items: center;
				flex: 1;
			}
			.enter-phone {
				flex: 1;
				margin-left: 10rpx;
				background: transparent;
				border: none;
				outline: none;
				font-size: 24rpx;
				.phone.error & {
					color: #f56c6c;
				}
			}
			.right {
				display: flex;
				justify-content: flex-end;
			}
		}
		.friend-btn-wrap {
			margin-top: 20rpx;
			margin-left: auto;
			margin-right: auto;
			.friend-btn{
				width: 100%;
				background-color: #3f89ff;
				color: #fff;
				font-size: 24rpx;
				font-weight: 600;
				padding: 18rpx 0;
				border-radius: 20rpx;
				border: none;
				&::after{//清除uniapp默认按钮样式
					border: none !important;
					border-radius: 15rpx !important;
				}
				&:active {//点击反馈
					background-color: #1a68e0;
					transform: scale(0.97);
				}
			}
		}
		
		.price-box {
			margin-top: 40rpx;
			padding: 0 20rpx;
			background-color: #ffffff;
			display: flex;
			align-items: center;
			justify-content: space-between;
			.left, .right{
				display: flex;
				align-items: center;
			}
			.right {
				justify-content: flex-end;
			}
			.text{
				font-size: 26rpx;
				margin-right: 20rpx;
			}
			.num{
				font-size: 34rpx;
				font-weight: 600;
				margin-right: 10rpx;
				color: #e00;
			}
			.question {
				
			}
		}
	}
	.guessKmTime {
		margin-top: 20rpx;
		padding: 0 30rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		.left{
			font-size: 20rpx;
			color: #999;
			text-align: center;
		}
	}
}
</style>